<?php

require_once 'utils.php';

class Error {
	const LVL_FATAL = 0;
	const LVL_ERROR = 1;
	const LVL_WARNING = 2;
	const LVL_INFO = 3;

	private $id;
	private $msg;
	private $lvl;
	private $location;

	private static $log;
	static function init(){
		self::$log = Logger::getLogger(__CLASS__);
	}


	public function __construct($message, $where = null, $uid = '-1', $level = self::LVL_WARNING){
		$this->id = $uid;
		$this->msg = $message;
		$this->lvl = $level;
		$this->location = $where;
	}

	public function setLocation($where){
		$this->location = $where;
	}

	public function toString(){
		$res = 'ERROR:\n'
			.'\tFROM:\t\t' . $this->id . '\n';

		if(!is_null($this->location))
			$res .= '\tHAPPENED IN: \t\t' . $this->location . '\n';

		$res .= '\tCONTENT:\t\t' . $this->msg;
		return $res;
	}

	public function toHtml(){
		$res = '<h3>ERROR:</h3><br/>'
			.'<p>FROM:' . $this->id . '</p><br/>';

		if(!is_null($this->location))
			$res .= '<p>HAPPENED IN: ' . $this->location . '</p><br/>';

		$res .= '<p>CONTENT:' . $this->msg . '</p>';
		return $res;
	}



	public function report(){
		self::save($this);
	}

	private static function save(Error $e){
		try {
			$stmt = DBManager::statementInsertError();
			$stmt->bindValue(':lvl', $e->lvl, PDO::PARAM_INT);
			$stmt->bindValue(':content', $e->toString(), PDO::PARAM_STR);
			$stmt->bindValue(':uid', $e->id, PDO::PARAM_STR);
			$stmt->execute();
			$stmt->closeCursor();
		} catch(PDOException $ex) {
			self::$log->fatal('Impossibile salvare l\'errore su database. Error: ' .$e
			.'\nErrore originale '. $e);
		}
	}

	private static function logError($e){
		switch($e->lvl){
		case LVL_FATAL :
			self::$log->fatal($e->toString());
			break;
		case LVL_ERROR:
			self::$log->error($e->toString());
			break;
		case LVL_WARNING:
			self::$log->warning($e->toString());
			break;
		case LVL_INFO:
			self::$log->info($e->toString());
			break;
		default:
			self::$log->fatal('L\'errore che si sta cercando di salvare non ha un livello di errore conosciuto');
		}
	}
}

Error::init();
?>
